package de.clapp.backend.requests;

import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.google.gson.reflect.TypeToken;

import de.clapp.backend.database.Conn;
import de.clapp.backend.database.Queries;
import de.clapp.data.Newsfeed;

public class NewsFeedRequest implements ServerRequest
{

    /**
     * 
     */
    private static final long serialVersionUID = -755806454474159163L;

    private int eventsFromPastXDays;

    private ArrayList<Newsfeed> newsFeedList;

    public NewsFeedRequest(int eventsFromPastXDays)
    {
        this.eventsFromPastXDays = eventsFromPastXDays;
    }

    @Override
    public ArrayList<Newsfeed> getItem()
    {
        return this.newsFeedList;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void setItem(Object item)
    {
        this.newsFeedList = (ArrayList<Newsfeed>) item;
    }

    @Override
    public Type getReturnType()
    {
        // TODO Auto-generated method stub
        return new TypeToken<ArrayList<Newsfeed>>()
        {
        }.getType();
    }

    @Override
    public Object execute()
    {
        Connection con = Conn.getInstance().serverCon;
        ArrayList<Newsfeed> newsfeedList = new ArrayList<Newsfeed>();
        PreparedStatement pstmt = null; 
        ResultSet rs = null;

        try
        {
            pstmt = con.prepareStatement(Queries.GET_NEWSFEEDS_FOR_PAST_DAYS);
            pstmt.setInt(1, -1 * this.eventsFromPastXDays);
            rs = pstmt.executeQuery();

            while (rs.next())
            {
                Newsfeed nf = new Newsfeed();

                nf.setNewsfeedid(rs.getInt("ID_NEWSFEED"));
                nf.setClubid(rs.getInt("CLUB"));
                nf.setTitle(rs.getString("TITLE"));
                nf.setContent(rs.getString("CONTENT"));
                nf.setPictureName(rs.getString("PICTURENAME"));
                nf.setEventdate(rs.getDate("EVENTDATE").getTime());

                newsfeedList.add(nf);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                pstmt.close();
            }
            catch (SQLException e1)
            {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try
            {
                rs.close();
            }
            catch (SQLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return newsfeedList;
    }

    // @Override
    // public Class<?> getReturnClass()
    // {
    // return new ArrayList<Newsfeed>().getClass();
    // }

}
